package com.hxd.buybooksystem.ui.activity

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.provider.MediaStore
import android.view.Gravity
import cn.bmob.v3.exception.BmobException
import com.hjq.dialog.InputDialog
import com.hjq.dialog.ToastDialog
import com.hjq.dialog.WaitDialog
import com.hxd.buybooksystem.R
import com.hxd.buybooksystem.base.common.MyActivity
import com.hxd.buybooksystem.bean.UserInfo
import com.hxd.buybooksystem.uitls.L
import com.vondear.rxtool.RxSPTool
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.datatype.BmobFile
import cn.bmob.v3.listener.*
import com.hjq.base.BaseDialog
import com.hjq.dialog.MenuDialog
import com.hjq.image.ImageLoader
import com.hxd.tabactivityfragment.util.StaticClassUtil
import com.hxd.tabactivityfragment.util.ThreadUtil
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.activity_user_info.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.support.v4.startActivity
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


class UserInfoActivity : MyActivity() {

    private val objectId: String? by lazy { RxSPTool.getString(this, "objectId") }
    private val spImagePath: String? by lazy { RxSPTool.getString(this, "imagePath") }
    private var imageFile:File? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_user_info
    }

    override fun getTitleId(): Int {
        return R.id.tb_title_userInfo
    }

    override fun initView() {

        /**
         * 用户头像
         */
        rl_image_userInfo.setOnClickListener {
            MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(arrayListOf("拍照", "从相册选择"))
                .setListener(object : MenuDialog.OnListener {
                    override fun onSelected(dialog: Dialog, position: Int, text: String) {
                        if (position == 0) {
                            fromCamera()
                        } else {
                            fromAlbum()
                        }
                    }

                    override fun onCancel(dialog: Dialog) {

                    }
                })
                .setGravity(Gravity.CENTER)
                .setAnimStyle(BaseDialog.AnimStyle.SCALE)
                .show()
        }

        /**
         * 昵称
         */
        rl_name_userInfo.setOnClickListener {
            MyInputDialog("请输入昵称", object : OnInputDialogListener {
                override fun inputDialogClick(content: String) {
                    tv_name_userInfo.text = content
                }
            })
        }

        /**
         * 性别
         */
        rl_gender_userInfo.setOnClickListener {
            MenuDialog.Builder(this)
                .setCancel(null) // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(arrayListOf("男", "女"))
                .setListener(object : MenuDialog.OnListener {

                    override fun onSelected(dialog: Dialog, position: Int, text: String) {
                        if (position == 0) {
                            tv_gender_userInfo.text = "男"
                        } else {
                            tv_gender_userInfo.text = "女"
                        }
                    }

                    override fun onCancel(dialog: Dialog) {

                    }
                })
                .setGravity(Gravity.CENTER)
                .setAnimStyle(BaseDialog.AnimStyle.SCALE)
                .show()
        }

        /**
         * 个人介绍
         */
        rl_describe_userInfo.setOnClickListener {
            MyInputDialog("请输入简介", object : OnInputDialogListener {
                override fun inputDialogClick(content: String) {
                    tv_describe_userInfo.text = content
                }
            })
        }

        /**
         * 手机号码
         */
        rl_phone_userInfo.setOnClickListener {
            MyInputDialog("请输入手机号", object : OnInputDialogListener {
                override fun inputDialogClick(content: String) {
                    tv_phoneNumber_userInfo.text = content
                }
            })
        }

        /**
         * 保存按钮
         */
        rl_address_userInfo.setOnClickListener {
            MyInputDialog("请输入地址", object : OnInputDialogListener {
                override fun inputDialogClick(content: String) {
                    tv_address_userInfo.text = content
                }
            })
        }

        /**
         * 保存按钮
         */
        btn_save_userInfo.setOnClickListener {
            updateImage()
        }
    }

    override fun initData() {
        if (objectId != "") {
            loadUserInfo()
        }
    }

    /**
     * 从相机选择
     */
    private fun fromCamera(){
        toast("从相机选择")
    }

    /**
     * 从相册选择
     */
    private fun fromAlbum(){
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, StaticClassUtil.ALBUM_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //调用相册
        if (requestCode == StaticClassUtil.ALBUM_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            callAlbum(data, iv_image_userInfo)
        }
    }

    /**
     * 调用相册功能
     */
    fun callAlbum(data: Intent, imageView: CircleImageView){
        ThreadUtil.runOnMainThread(Runnable {
            val selectedImage = data.data
            val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(selectedImage, filePathColumns, null, null, null)
            cursor.moveToFirst()
            val columnIndex = cursor.getColumnIndex(filePathColumns[0])
            //文件路径
            val imagePath = cursor.getString(columnIndex)
            //进行图片压缩
            Luban.with(this).load(imagePath).ignoreBy(100).setCompressListener(object : OnCompressListener {
                override fun onSuccess(file: File) {
                    ImageLoader.loadCircleImage(imageView, file.path)
                    imageFile = file
                }


                //当压缩过程出现问题时调用
                override fun onError(e: Throwable?) {

                }

                //当压缩过程出现开始时
                override fun onStart() {
                }
            }).launch()
            cursor.close()
        })
    }


    /**
     * 自定义输入框
     */
    private fun MyInputDialog(title: String, InputDialogListener: OnInputDialogListener) {
        InputDialog.Builder(this)
            .setTitle(title)
            .setConfirm("确定")
            .setCancel("取消") // 设置 null 表示不显示取消按钮
            .setListener(object : InputDialog.OnListener {
                override fun onConfirm(dialog: Dialog, content: String) {
                    InputDialogListener.inputDialogClick(content)
                }

                override fun onCancel(dialog: Dialog) {

                }
            })
            .show()
    }

    /**
     * 用于首次添加用户信息
     */
    private fun addUserInfo(imageUrl: String? = null) {
        val userInfo = UserInfo(
            tv_name_userInfo.text.toString(),
            tv_gender_userInfo.text.toString(),
            tv_describe_userInfo.text.toString(),
            tv_phoneNumber_userInfo.text.toString(),
            tv_address_userInfo.text.toString(),
            imageUrl
        )
        waitDialog
        userInfo.save(object : SaveListener<String>() {
            override fun done(objectId: String?, e: BmobException?) {
                waitDialog.dismiss()
                if (e == null) {
                    L.i("用户信息添加成功，返回objectId为：$objectId")
                    RxSPTool.putString(getActivity(), "objectId", objectId)
                    successDialog
                } else {
                    L.i("用户信息添加失败：" + e.errorCode)
                    errorDialog
                }


            }
        })
    }

    /**
     * 用于后续的更新用户信息
     */
    private fun updateUserInfo(imageUrl:String? = null) {
        val userInfo = UserInfo(
            tv_name_userInfo.text.toString(),
            tv_gender_userInfo.text.toString(),
            tv_describe_userInfo.text.toString(),
            tv_phoneNumber_userInfo.text.toString(),
            tv_address_userInfo.text.toString(),
            imageUrl
        )
        waitDialog
        userInfo.update(objectId, object : UpdateListener() {
            override fun done(e: BmobException?) {
                waitDialog.dismiss()
                if (e == null) {
                    L.i("用户信息更新成功:" + userInfo.updatedAt)
                    successDialog
                } else {
                    L.i("用户信息更新失败：" + e.errorCode)
                    errorDialog
                }

            }
        })
    }

    /**
     * 载入用户信息
     */
    private fun loadUserInfo() {
        val bmobQuery = BmobQuery<UserInfo>()
        waitDialog
        bmobQuery.getObject(objectId, object : QueryListener<UserInfo>() {
            override fun done(userInfo: UserInfo, e: BmobException?) {
                waitDialog.dismiss()
                if (e == null) {
                    L.i("查询成功, $userInfo")
                    tv_name_userInfo.text = userInfo.name
                    tv_gender_userInfo.text = userInfo.gender
                    tv_describe_userInfo.text = userInfo.desc
                    tv_phoneNumber_userInfo.text = userInfo.phone
                    tv_address_userInfo.text = userInfo.address
                    if (userInfo.image != null){
                        ImageLoader.loadCircleImage(iv_image_userInfo,userInfo.image)
                    }
                } else {
                    L.i("查询失败：" + e.errorCode)
                }
            }
        })
    }

    /**
     * 输入框接口
     */
    interface OnInputDialogListener {
        fun inputDialogClick(content: String)
    }


    /**
     * 上传图片
     */
    private fun updateImage(){
        //判断是否是更新还是创建操作
        if(objectId != ""){
            //更新
            //判断是否从相册中选中了一张图片
            if(imageFile != null){
                val bmobFile = BmobFile(imageFile)
                waitImageDialog
                bmobFile.uploadblock(object : UploadFileListener() {
                    override fun done(e: BmobException?) {
                        waitImageDialog.dismiss()
                        if(e==null){
                            //bmobFile.getFileUrl()--返回的上传文件的完整地址
                            successDialog
                            L.i("上传文件成功:" + bmobFile.fileUrl)
                            RxSPTool.putString(getActivity(), "imagePath", bmobFile.fileUrl)
                            updateUserInfo(bmobFile.fileUrl)
                        }else{
                            errorDialog
                            L.i("上传文件失败：" + e.errorCode)
                        }
                    }
                })
            }else {
                //判断是否更新图片
                if(spImagePath  != ""){
                    updateUserInfo(spImagePath)
                }else{
                    updateUserInfo(null)
                }
            }
        }else{
            //创建
            //判断是否从相册中选中了一张图片
            if(imageFile != null){
                val bmobFile = BmobFile(imageFile)
                waitImageDialog
                bmobFile.uploadblock(object : UploadFileListener() {
                    override fun done(e: BmobException?) {
                        waitImageDialog.dismiss()
                        if(e==null){
                            //bmobFile.getFileUrl()--返回的上传文件的完整地址
                            successDialog
                            L.i("上传文件成功:" + bmobFile.fileUrl)
                            RxSPTool.putString(getActivity(), "imagePath", bmobFile.fileUrl)
                            addUserInfo(bmobFile.fileUrl)
                        }else{
                            errorDialog
                            L.i("上传文件失败：" + e.errorCode)
                        }
                    }
                })
            }else {
                updateUserInfo(null)
            }
        }
    }

    override fun onBackPressed() {
        startActivity<MainActivity>()
        finish()
    }
}
